<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>table模块快速使用</title>
  <link rel="stylesheet" href="../layui/dist/css/layui.css" media="all">
</head>
<style>
  /* #usertab{
        margin-top: 10px;
    } */
  .layui-form {
    margin-top: 10px;
    position: relative;
    height: 120px;
  }

  .layui-form-item {
    top: 15px;
    position: absolute;
  }

  .layui-form-item .layui-inline {
    flex: 1;
  }

  .layui-card-body {
    left: 20px;
    height: 30px;
  }

  .layui-table-cell{
    text-align:center;
    height: auto;
  }

  /* .layui-form-item .layui-form-select{
      width: 200px;
    } */
</style>

<body>
  <div class="layui-fluid">
    <div class="layui-card">
      <div class="layui-form layui-card-header layuiadmin-card-header-auto">
        <form action="">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">评论ID</label>
              <div class="layui-input-block">
                <input type="text" name="commentId" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">学号</label>
              <div class="layui-input-block">
                <input type="text" name="userId" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">评论类型</label>
              <div class="layui-input-block" style="width: 200px;">
                <select name="commentType">
                  <option value="不限">不限</option>
                  <option value="activity">活动评论</option>
                  <option value="article">文章评论</option>
                  </select>
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">关联ID</label>
              <div class="layui-input-block">
                <input type="text" name="targetId" placeholder="请输入" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">评论内容</label>
              <div class="layui-input-block">
                <input type="text" name="content" placeholder="请输入" autocomplete="off" class="layui-input" >
              </div>
            </div>
            <div class="layui-inline">
              <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY-user-front-search">
                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
              </button>
            </div>
          </div>
        </form>
      </div>

      <div class="layui-card-body">
        <div style="padding-bottom: 10px;">
          <button class="layui-btn layuiadmin-btn-useradmin" data-type="batchdel">删除</button>
          <button class="layui-btn layuiadmin-btn-useradmin" data-type="edit">编辑</button>
        </div>


      </div>
      <table id="commenttab" lay-filter="commenttab"></table>
    </div>
  </div>

  <script src="./JS/utils/request.js"></script>
  <script src="./JS/utils/auth.js"></script>
  <script src="../layui/layui.all.js"></script>
  <script>
    layui.use(['form', 'table', 'layer'], function () {
      var table = layui.table;
      var form = layui.form;
      var $ = layui.$;
      var layer = layui.layer;
      const token = localStorage.getItem('token')
      //第一个实例
      table.render({
        elem: '#commenttab'
        , title: '评论列表'
        , height: 500
        , url: '/comments/list'
        //数据接口
        , page: true //开启分页
        ,limits:[10]
        , cols: [[ //表头
          { type: 'checkbox', sort: true},
          { title: '序号', type: 'numbers', autoSort: true },
          { field: 'commentId', title: '评论ID', sort: true}
          , { field: 'commentType', title: '评论类型',templet: function(d){

const statusMap = {
    "article": '<span style="color:#00EC00">文章评论</span>',
    "activity": '<span style="color:#ffb800">活动评论</span>'
}
return statusMap[d.commentType] || '未知状态';
}}
          , { field: 'userId', title: '用户编号'}
          , { field: 'targetId', title: '活动/文章关联ID'}
          , { field: 'likeCount', title: '获赞总数'}
          , { field: 'content', title: '评论内容'}
          , { field: 'parentCommentId', title: '关联父ID',sort:true}
          , { field: 'createTime', title: '创建时间',  sort: true }
          , { field: 'updateTime', title: '更新时间',  sort: true }
        ]],
        headers: {
       'Authorization': token
  }
        , parseData: function (res) { //res 即为原始返回的数据
          console.log(res)
          return {
            "code": res.code, //解析接口状态
            "msg": res.msg, //解析提示文本
            "count": res.data.totalCount, //解析数据长度
            "data": res.data.list //解析数据列表
          }
        }
        //
        , done: function () {
          $(".layui-table-main tr").each(function (index, val) {
            $(".layui-table-fixed").each(function () {
              $($(this).find(".layui-table-body tbody tr")[index]).height($(val).height());
            });
          });
          $(".layui-table-header tr").each(function (index, val) {
            $(".layui-table-fixed").each(function () {
              $($(this).find(".layui-table-header thead tr")[index]).height($(val).height());
            });
          });
        }

      })

      form.on('submit(LAY-user-front-search)', function (data) {
        // layer.msg(JSON.stringify(data.field));
        // console.log(data.field);

        // 执行表格重载（带参数）
        table.reload('commenttab', {
          where: {
            commentId: data.field.commentId,
            userId: data.field.userId,
            commentType: data.field.commentType,
            content: data.field.content,
            targetId:data.field.targetId
          },    // 查询参数
          method: 'get',
          headers:{
              'Authorization':localStorage.getItem('token')
    },
          page: { curr: 1 }      // 重置到第一页
        });
        $('input').val('')
        return false;
      });


      // 表格复选框点击删除监听事件
      $('button[data-type="batchdel"]').click(function () {
        var checkData = table.checkStatus('commenttab').data;
        // 提取userId生成数组
        var commentIds = checkData.map(function (item) {
          return item.commentId;
        });
        // 转换为逗号分隔字符串
        var commentIdsStr = commentIds.join(',');
        console.log(commentIdsStr)
        if (commentIds.length === 0) {
          layer.msg('请至少选择一项');
          return;
        }
        deleteComment(commentIdsStr)
      })

      // 编辑事件监听
      $('button[data-type="edit"]').click(function(){
        var checkData = table.checkStatus('commenttab').data;
        console.log(checkData)
        // 验证选择数量
        if(checkData.length !== 1){
          return layer.msg('请选择一条要编辑的数据');
        }else{
          // 获取学号
          var commentId = checkData[0].commentId;

          // 打开弹出层
          layer.open({
            type: 2,
            title: '修改评论信息 - 评论ID：' + commentId,
            content: 'edit.html?commentId=' + commentId,
            area: ['600px', '300px'],
            btn: ['保存', '取消'],
            yes: function (index,layero) {
              // console.log(layero)
              // 获取iframe窗口对象
              var iframeWin = layero.find('iframe')[0].contentWindow;

              // 调用子页面的提交方法
              iframeWin.updateForm(function(success){
                if(success){
                  layer.close(index);
                  layer.msg('更新成功');
                  table.reload('commenttab', {
                    // 不传递任何参数，自动保留当前查询条件和分页状态
                    page: {
                      curr: 1
                    }
                  });
                }
              });

            },
            success: function(layero, index){
              // 获取iframe窗口对象
              var iframeWin = layero.find('iframe')[0].contentWindow;

              // 传递选中数据到子页面
              iframeWin.initFormData(checkData[0]);
            }
          });
        }


      });

      // 彻底删除用户函数
      function deleteComment(commentIdsStr) {
        layer.confirm('确定删除该评论？', function (index) {
          $.ajax({
            url: '/comments/delete/' + commentIdsStr, // 路径参数
            type: 'DELETE',
            headers:{
              'Authorization':localStorage.getItem('token')
    },
            success: function (res) {
              layer.msg('删除成功', { icon: 1 });
              // 刷新表格数据
              layui.table.reload('commenttab');
            },
            error: function (xhr) {
              layer.msg('删除失败: ' + xhr.statusText, { icon: 2 });
            }
          });
          layer.close(index);
        });
      }





    });
  </script>
  <script>

  </script>
</body>

</html>